<?php


namespace App\Logic\Order\Form;

use App\Core\BaseListForm;
use App\Core\Exception\DefaultException;
use App\Model\Member\MemberModel;
use App\Model\Order\OrderModel;
use App\Model\Order\OrderTaskModel;
use App\Model\Order\OrderTaskStatisticsModel;
use App\Model\UserModel;
use App\Util\CommonHelper;
use App\Util\UserIdentityHelper;
use EasySwoole\Mysqli\QueryBuilder;

class OrderTaskStatisticsListForm extends BaseListForm
{
    public $id;
    public $user_id;
    public $username;
    public $score;
    public $before_score;
    public $after_score;
    public $remark;
    public $type;
    public $month;
    public $object_id;
    public $referrer_profit_user_id;
    public $created_at;
    public $start_created_at;
    public $end_created_at;
    public $group;
    public $date;
    public $range;


    /**
     * 收益账户积分变动列表
     * @return \App\Core\Output
     * @throws DefaultException
     * @throws \EasySwoole\Mysqli\Exception\Exception
     * @throws \EasySwoole\ORM\Exception\Exception
     * @throws \Throwable
     */
    public function lists()
    {
        $where      = [];
        $table_date = '';//月份分表
        if (UserIdentityHelper::getType() == UserModel::TYPE_INSIDE) {
            /**后台管理员*/
            if ($this->checkField($this->user_id)) {
                $where['user_id'] = $this->user_id;
            }
            if ($this->checkField($this->username)) {
                if (!$member = MemberModel::create()->getOne(['username' => $this->username])) {
                    throw new DefaultException('用户不存在');
                }
                $where['user_id'] = $member->id;
            }
        } else {
            $this->user_id    = UserIdentityHelper::getId();
            $where['user_id'] = $this->user_id;
        }

        if ($this->checkField($this->month)) {
            $month = $this->month;
        } else {
            $month = date('Y-m');
        }

        $month_start_date   = $month . '-01 00:00:00';
        $month_end_date     = date('Y-m-t', strtotime($month)) . ' 23:59:59';
        $where['task_date'] = [[$month_start_date, $month_end_date], 'between'];


        $model = OrderTaskStatisticsModel::makeQueryModel($where, [], $this->getPagination());
//        $fields = ["`task_date`", '`user_id`', '`quantity`', '`finished_order_count`', '`total_user_profit`'];
//
//        $model->field($fields);
        $model->order('`task_date`', 'DESC');

        $modelResult = $model->all();

        $list    = [];
        $user_id = null;
        foreach ($modelResult as $v) {
            $user_id             = $v->user_id;
            $item                = [
                'user_id'              => $v->user_id,
                'date'                 => $v->task_date,
                'return_date'          => date('Y-m-d', strtotime($v->task_date) + 7 * 86400),
                'quantity'             => $v->quantity,
                'order_amount'         => $v->order_amount,
                'finished_order_count' => $v->finished_order_count,
                'total_user_profit'    => $v->total_user_profit,
                'created_at'           => $v->created_at,
            ];
            $list[$v->task_date] = $item;
        }

        if (!empty($list)) {
            $firstDay = $month . '-01';
            $firstDay = date('Y-m-01', strtotime($firstDay));
            $lastDay  = date('Y-m-t', strtotime($firstDay));
            /**
             * 循环遍历$firstDay所在月份的所有日期
             * 从$firstDay开始，直到该月的最后一天（$lastDay）
             * 每次循环增加一天（86400秒）
             */
            $data = [];
            for ($i = strtotime($lastDay); $i >= strtotime($firstDay); $i -= 86400) {
                $day = date('Y-m-d', $i);
                if (isset($list[$day])) {
                    $data[] = $list[$day];
                } else {
                    $data[] = [
                        'user_id'              => $user_id,
                        'date'                 => $day,
                        'return_date'          => '-',
                        'quantity'             => 0,
                        'order_amount'         => 0,
                        'finished_order_count' => 0,
                        'total_user_profit'    => 0,
                        'created_at'           => '-',
                    ];
                }
            }
            $list = $data;
        }

        $total                     = $model->lastQueryResult()->getTotalCount();
        $pagination                = $this->getPagination();
        $pagination['total_count'] = $total;

        $result = [
            'list'       => $list,
            'pagination' => $pagination
        ];
        return $result;
    }

}
